package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.model.LoginModel;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.edt_account)
    EditText edt_account;
    @BindView(R.id.edt_password)
    EditText edt_password;
    @BindView(R.id.btn_login)
    Button btn_login;
    LoginModel loginModel;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.login_blue));
    }

    @Override
    public void init() {
        loginModel = new LoginModel(this);
        loginModel.setMobileEdit(edt_account);
        loginModel.setPasswordEdit(edt_password);
        loginModel.setConfirm(btn_login);
        loginModel.clickLogin(btn_login, edt_account, edt_password);
        if (SharedPreferencesUtils.getKey(this)[0] != null && SharedPreferencesUtils.getKey(this)[0].length() > 5) {
            openActivity(MainActivity.class);
            finish();
        }
    }


    @OnClick(R.id.tv_forgot)
    void clickForgot() {
        openActivity(ForgotActivity.class);
    }

    @OnClick(R.id.tv_register)
    void clickRegister() {
        openActivity(RegisterActivity.class);
    }

    @OnClick(R.id.tv_num)
    void clickTel() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                e.onNext("");
            }
        }).compose(RxSchedulers.lifecycle(this)).throttleFirst(1, TimeUnit.SECONDS)
                .compose(rxPermissions.ensureEach(Manifest.permission.CALL_PHONE)).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getResources().getString(R.string.phone)));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }


}
